#!/bin/bash
function s1_read_last_two_bytes_of_a_mbr_backup_file(){
   last_two_bytes=$(tail -c 2 "$1")
   if [ "$last_two_bytes" == "$(echo -e '\x55\xAA')" ];then
       echo "YES"
   else
       echo "NO"
   fi
}

function s2_read_mbr_partition_table_info(){
   local device="$1"
   for i in {0..3}; do
      offset=$((446 + 16 * i))
      start_sector=$(dd if="$device" bs=1 skip=$((offset+ 8)) count=4 2>/dev/null | od -t u4 -An | tr -d ' \n')
      if [[ ! $start_sector =~ ^[0-9]+$ ]] || [[ "$start_sector" -eq 0 ]];then
          continue
      fi
      local size_sector=$(dd if="$device" bs=1 skip=$((offset + 12)) count=4 2>/dev/null | od -t u4 -An | tr -d ' /n')
      local end_sector=$((start_sector + size_sector -1))
      echo "$start_sector $end_sector"
   done
}

function s3_parse_partition_info(){
     local fdisk_output
     fdisk_output=$(cat)
     local disk_size_bytes
     disk_size_bytes=$(echo "$fdisk_output" | awk '/Disk \/dev\/vda:/ {print $5}')
     local disk_size_sectors
     disk_size_sectors=$(echo "$fdisk_output" | awk  '/Disk \/dev\/vda:/ {print $7}')
     local physical_sector_size
     physical_sector_size=$(echo "$fdisk_output" |awk '/Sector size/ {print $4}')
     local first_partition_sector
     first_partition_start_sector=$(echo "$fdisk_output" | awk '/\/dev\/vda1/ {print $3}')
     local first_partition_end_sector
     first_partition_end_sector=$(echo "$fdisk_output" | awk '/\/dev\/vda1/ {print $4}')
     local first_partition_type
     first_partition_type=$(echo "$fdisk_output" | awk '/\/dev\/vda1/ {print $8}')
     echo "disk size in bytes:$disk_size_bytes"
     echo "disk size in sectors:$disk_size_sectors"
     echo "physical sector size in bytes:$physical_sector_size"
     echo "first partition start sector id:$first_partition_start_sector"
     echo "first partition end sector id:$first_partition_end_sector"
     echo "first partition type:$first_partition_type" 
}

function s4_run_passwd_as_plain_user_and_get_status() {
     path_to_oversleeping=$(which oversleeping)
     sudo chown root "$path_to_oversleeping"
     sudo chmod u+s "$path_to_oversleeping"
     "$path_to_oversleeping" &
     sleep 1
     ps -o uid,euid,ruid -C oversleeping | awk 'NR>1 {print $1","$2","$3}'
}

function s5_add_a_scheduled_task(){
     touch $HOME/test_crontab;
     { crontab -l; echo "*/5 * * * * date +\%Y\%m\%d_\%H\%M\%S >> $HOME/test_crontab"; } | crontab -
}

